local app = require 'app'
local game = app.game.running
local GameObjectExtension = CS.Blaze.GameObjectExtension
local Vector3 = CS.UnityEngine.Vector3

local mini_record_shower = game.ui.element()

mini_record_shower.store_watchers = 
{
    gameplay = 
    {
        ["$"] = function(self, store, state)
            if state.scene then
                self:update(state.records)
            end
        end,

        ["阶段变更"] = function(self, store, state)
            if state.phase_id == game.util.consts.PHASE_PAYOUT then
                self:update(state.records)
            end
        end,

        ['同步游戏记录'] = function(self, store, state)
            self:update(state.records)
        end,

        ["恢复游戏场景"] = function(self, store, state, args)
            self:update(state.records)
        end,
    }
}

function mini_record_shower:ctor()
    self.res = "club.threecard.baccarat/ui/ingame.b:mini_record_shower"
    self.x = 12
    self.y = 999
    self.lines = {}
    self.nodes = {}
end

function mini_record_shower:clear()
    self.lines = {}
    for _, node in ipairs(self.nodes) do
        GameObjectExtension.ReturnToPool(node)
    end
    self.nodes = {}
end

function mini_record_shower:update(records)
    self:clear()

    nodes = 
    {
        [1] = self.node1,
        [2] = self.node3,
        [5] = self.node2
    }

    times = 
    {
        [1] = 0,
        [2] = 0,
        [5] = 0
    }

    local space_x = 18
    local space_y = -18

    local last_id = -1
    for _, data in ipairs(records) do
        for _, id in ipairs(data.hits) do
            if id == 1 or id == 2 or id == 5 then
                times[id] = times[id] + 1
                if last_id ~= id then
                    table.insert(self.lines, {id = id, count = 0})
                end
                self.lines[#self.lines].count = self.lines[#self.lines].count + 1
                last_id = id
                break
            end
        end
    end

    local start_index = (#self.lines > self.x) and (#self.lines - self.x+1) or 1
    local line_index = 0
    for i = start_index, #self.lines do
        local line = self.lines[i]
        for j = 1, line.count do
            local node = GameObjectExtension.GetFromPool(nodes[line.id])
            node.transform:SetParent(self.content, false)
            node.transform.localPosition = Vector3(line_index * space_x, (j-1) * space_y, 0)
            table.insert(self.nodes, node)
        end
        line_index = line_index + 1
    end

    self.banker_txt.text = string.format('%s', times[1])
    self.tie_txt.text = string.format('%s', times[5])
    self.player_txt.text = string.format('%s', times[2])
end

return mini_record_shower